package com.viu.technology.service.auth;

import com.viu.technology.dto.JwtUser;
import com.viu.technology.po.User;
import com.viu.technology.service.user.UserService;
import com.viu.technology.service.user.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    private static Logger log = LoggerFactory.getLogger(JwtUserDetailsServiceImpl.class);

    @Autowired
    @Lazy
    private UserService userService;

    public JwtUserDetailsServiceImpl(){
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //log.info("开始验证用户名密码");
        User user = null;
        if (username.length() == 32) {
            log.info("get user by id");
            user= userService.getUserAndRoleById(username);
        } else if (username.length() == 11) {
            log.info("get user by phone");
            user = userService.getUserAndRoleByPhone(username);
        }

        log.info("user:" + user);

        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        }else{
            return user;
        }
    }
}
